﻿using DataAccess.DAL;
using DataAccess.DTO;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Agent.Controllers
{
    public class LoginController : BaseController
    {
 

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        
        public ActionResult Index()
        {
            return View();
        }
       

        [HttpPost]
        public JsonResult Login(string username = "", string password = "", string verify1="")
        {
            if (username.Trim() == "" || password.Trim()=="")
                return Json(new Result { State = false, Message = "用户名或密码不正确" });
            
            if (verify1 == "")
                return Json(new Result { State = false, Message = "请输入正确的验证码" });
            if(!CheckVerifyCode(verify1))
                return Json(new Result { State = false, Message = "请输入正确的验证码" });
          
            UserSession session =  new AgencyUsersDAL().LoginSession(username.Trim(), password.Trim(),SysConfig.promoter_id);
            if (session == null)
                return Json(new Result { State = false, Message = "用户名或密码不正确" });

            CookieHelp.DeleteCookie(CookieHelp.UserCookieKey);
            string cookie = XYD.Common.EncodeSecurity.EncryptString(XYD.Common.JsonHelper.SerializerJson<UserSession>(session));

            CookieHelp.WriteCookie(CookieHelp.UserCookieKey, cookie, 7);
            return Json(new Result { State = true, Message = "登录成功", Datas = cookie });
        }
        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        public ActionResult OutLogin()
        {
            CookieHelp.DeleteCookie(CookieHelp.UserCookieKey);
            return Redirect("/login.html");
        }
        public static bool CheckVerifyCode(string verifyCode)
        {
            if (System.Web.HttpContext.Current.Request.Cookies["VerifyCode"] == null)
            {
                RemoveVerifyCookie();
                return false;
            }
            bool flag = string.Compare(XYD.Common.EncodeSecurity.DecryptString(System.Web.HttpContext.Current.Request.Cookies["VerifyCode"].Value), verifyCode, true, CultureInfo.InvariantCulture) == 0;
            RemoveVerifyCookie();
            return flag;
        }
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult VerifyCodeImage()
        {
            try
            {
                base.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
                string text =CreateVerifyCode(4);
                int num = 45;
                int num2 = text.Length * 20;
                System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(num2 - 3, 40);
                System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap);
                graphics.Clear(System.Drawing.Color.AliceBlue);
                graphics.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Gray, 0f), 0, 0, bitmap.Width - 1, bitmap.Height - 3);
                System.Random random = new System.Random();
                System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.LightGray, 0f);
                for (int i = 0; i < 50; i++)
                {
                    int x = random.Next(0, bitmap.Width);
                    int y = random.Next(0, bitmap.Height);
                    graphics.DrawRectangle(pen, x, y, 1, 1);
                }
                char[] array = text.ToCharArray();
                System.Drawing.StringFormat stringFormat = new System.Drawing.StringFormat(System.Drawing.StringFormatFlags.NoClip);
                stringFormat.Alignment = System.Drawing.StringAlignment.Center;
                stringFormat.LineAlignment = System.Drawing.StringAlignment.Center;
                System.Drawing.Color[] array2 = new System.Drawing.Color[]
				{
					System.Drawing.Color.Black,
					System.Drawing.Color.Red,
					System.Drawing.Color.DarkBlue,
					System.Drawing.Color.Green,
					System.Drawing.Color.Brown,
					System.Drawing.Color.DarkCyan,
					System.Drawing.Color.Purple,
					System.Drawing.Color.DarkGreen
				};
                for (int j = 0; j < array.Length; j++)
                {
                    int num3 = random.Next(7);
                    random.Next(4);
                    System.Drawing.Font font = new System.Drawing.Font("Microsoft Sans Serif", 17f, System.Drawing.FontStyle.Bold);
                    System.Drawing.Brush brush = new System.Drawing.SolidBrush(array2[num3]);
                    System.Drawing.Point point = new System.Drawing.Point(14, 11);
                    float num4 = (float)random.Next(-num, num);
                    graphics.TranslateTransform((float)point.X, (float)point.Y);
                    graphics.RotateTransform(num4);
                    graphics.DrawString(array[j].ToString(), font, brush, 1f, 10f, stringFormat);
                    graphics.RotateTransform(-num4);
                    graphics.TranslateTransform(2f, (float)(-(float)point.Y));
                }
                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
                bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Gif);

                return File(memoryStream.ToArray(), "image/gif");
            }
            catch
            {
            }
            finally
            {
                System.GC.Collect();
            }
            return null;

        }
        public static string CreateVerifyCode(int length)
        {
            string text = string.Empty;
            Random random = new Random();
            while (text.Length < length)
            {
                char ch;
                int num = random.Next();
                if ((num % 3) == 0)
                {
                    ch = (char)(0x61 + ((ushort)(num % 0x1a)));
                }
                else if ((num % 4) == 0)
                {
                    ch = (char)(0x41 + ((ushort)(num % 0x1a)));
                }
                else
                {
                    ch = (char)(0x30 + ((ushort)(num % 10)));
                }
                if ((((ch != '0') && (ch != 'o')) && ((ch != '1') && (ch != '7'))) && (((ch != 'l') && (ch != '9')) && ((ch != 'g') && (ch != 'I'))))
                {
                    text = text + ch.ToString();
                }
            }
            RemoveVerifyCookie();
            HttpCookie cookie = new HttpCookie("VerifyCode")
            {
                Value =  XYD.Common.EncodeSecurity.EncryptString(text)
            };
            System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
            return text;
        }
        private static void RemoveVerifyCookie()
        {
           System.Web.HttpContext.Current.Response.Cookies["VerifyCode"].Value = null;
           System.Web.HttpContext.Current.Response.Cookies["VerifyCode"].Expires = new DateTime(0x777, 10, 12);
        }
	}
}